﻿using AJWPFAdmin.Core.Models;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using FluentFTP;
using Masuit.Tools.Net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace AJWPFAdmin.Core.Utils
{
    public static class FtpUtil
    {
        /// <summary>
        /// 创建ftp连接(异步)
        /// </summary>
        /// <returns></returns>
        public static async Task<AsyncFtpClient> GetAsyncFtpClient(FtpOptions options)
        {
            var ftpClient = new AsyncFtpClient(options.Host);
            if (options.Port > 0)
            {
                ftpClient.Port = options.Port;
            }
            if (!string.IsNullOrEmpty(options.User) && !string.IsNullOrEmpty(options.Password))
            {
                ftpClient.Credentials = new NetworkCredential(options.User, options.Password);
            }
            ftpClient.Encoding = Encoding.UTF8;
            ftpClient.Config.DataConnectionType = options.Active ? FtpDataConnectionType.AutoActive : FtpDataConnectionType.AutoPassive;
            await ftpClient.Connect();

            //await ftpClient.CreateDirectory(options.WorkingDirectory);
            //await ftpClient.SetWorkingDirectory(options.WorkingDirectory);
            return ftpClient;
        }

        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="sourcePath">文件源路径</param>
        /// <param name="destPath">上传到指定的ftp文件夹路径</param>
        public static async Task UploadFile(FtpOptions options,string sourcePath, string destPath)
        {
            if (!File.Exists(sourcePath))
                return;
            using var ftpClient = await GetAsyncFtpClient(options);
            try
            {
                //var fileInfo = new FileInfo(sourcePath);
                await ftpClient.UploadFile(sourcePath, $"{destPath}", createRemoteDir: true);
            }
            finally
            {
                if (ftpClient.IsConnected)
                {
                    //关闭
                    await ftpClient.Disconnect();
                    ftpClient.Dispose();
                }
            }
        }
    }
}
